package pathfinding;

import java.io.Serializable;
import java.util.List;

import com.sun.sgs.app.AppContext;
import com.sun.sgs.app.DataManager;
import com.sun.sgs.app.ManagedObject;
import com.sun.sgs.app.ManagedReference;

public class DStarGridDiagSimpleTabled extends DStarGridDiagSimple implements ManagedObject, Serializable {

	private boolean reservationsChanged = false;
	
	public DStarGridDiagSimpleTabled(GridCell start, GridCell goal, ManagedReference<SpaceTimeReservationTable> tableRef) {
		super(start, goal);
		DataManager dataManager = AppContext.getDataManager();
		dataManager.markForUpdate(this);
		this.tableRef = tableRef;
	}
	
	ManagedReference<SpaceTimeReservationTable> tableRef;

	private static final long serialVersionUID = 1L;

	@Override
	protected boolean isReserved(GridCell c, long timeStart, long timeEnd) {
		return tableRef.get().isReserved(c, timeStart, timeEnd);
	}
	
	public void changedToReserved(GridCell c) {
		for (GridCell sPrime : nbrs(c)) {
            flagChange(sPrime, c, baseCost(sPrime, c), reservedCost);
            flagChange(c, sPrime, baseCost(c, sPrime), reservedCost);
        }
        
		reservationsChanged = true;
		
	}
	
	public void changedToFree(GridCell c) {
        for (GridCell sPrime : nbrs(c)) {
            flagChange(sPrime, c, reservedCost, c(sPrime, c));
            flagChange(c, sPrime, reservedCost, c(c, sPrime));
        }

		reservationsChanged = true;
	}
	
	public boolean needsUpdate()
	{
		return reservationsChanged;
	}
	
	public List<GridCell> plan() {
		reservationsChanged = false;
		return super.plan();
	}
}
